package main

import (
	"fmt"
	"github.com/thinkeridea/go-extend/exnet"
	"io"
	"net/http"
	"os"
)

func main() {
	start()
}

// 启动监听端口
func start() {
	// 路由地址
	http.HandleFunc("/", rootHandle)
	http.HandleFunc("/healthz", healthz)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println(err)
	}
}

// 根处理函数
func rootHandle(w http.ResponseWriter, r *http.Request) {
	//fmt.Println("root handler")
	/*user := r.URL.Query().Get("user")
	if user != "" {
		io.WriteString(w, fmt.Sprintf("hello [%s]\n", user))
	} else {
		io.WriteString(w, "hello !")
	}*/
	// 获取request的header放入response
	for k, v := range r.Header {
		io.WriteString(w, fmt.Sprintf("%s=%s\n", k, v))
	}
	// 获取环境变量
	home := os.Getenv("HOME")
	io.WriteString(w, fmt.Sprintf("os home = %s", home))
	// 获取客户端的ip
	getClientIp(r)
}

// 健康检查
func healthz(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "ok\n")
}

// 获取客户端ip
func getClientIp(r *http.Request) {
	ip := exnet.ClientPublicIP(r)
	if ip == "" {
		ip = exnet.ClientIP(r)
	}
	fmt.Sprintf("client ip = %s", ip)
}
